﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sobiens.Connectors.Common;
using Sobiens.Connectors.Entities.Settings;
using Sobiens.Connectors.Common.Interfaces;
using Sobiens.Connectors.Entities;
using Sobiens.Connectors.WPF.Controls.Search;
using Sobiens.Connectors.Entities.Search;
using Sobiens.Connectors.Entities.Interfaces;
using Sobiens.Connectors.Entities.Documents;
using Sobiens.Connectors.WPF.Controls.Settings;
using Sobiens.Connectors.WPF.Controls.Selectors;

namespace Sobiens.Connectors.WPF.Controls
{
    /// <summary>
    /// Interaction logic for SearchExplorer.xaml
    /// </summary>
    public partial class SearchExplorer : HostControl, ISearchExplorer
    {
        private bool isLeftClick = false;
        public bool IsDataLoaded { get; set; }
        public SiteSettings SiteSettings { get; set; }
        public DocumentTemplates DocumentTemplates { get; set; }

        private Dictionary<string, SearchFilters> CurrentSearchFilters = new Dictionary<string, SearchFilters>();
        private Dictionary<string, Dictionary<string, SearchFilters>> SearchFiltersCollection = new Dictionary<string, Dictionary<string, SearchFilters>>();

        private ApplicationTypes SelectedApplicationType;
        private DocumentTemplate SelectedDocumentTemplate = null;
        private DocumentTemplateMapping SelectedDocumentTemplateMapping = null;

        public void RefreshControls()
        {
            if (this.IsDataLoaded == false)
            {
                LoadTemplateContentTypes();
                this.IsDataLoaded = true;
            }
        }

        private void LoadTemplateContentTypes()
        {
            SearchFiltersCollection.Clear();
            SelectedContentTypeLabel.Content = "Please select a content type";

            this.LoadApplicationTemplateContentTypes(TemplateContentTypeSelectorCM, ApplicationTypes.General);
            this.LoadApplicationTemplateContentTypes(TemplateContentTypeSelectorCM, ApplicationTypes.Word);
            this.LoadApplicationTemplateContentTypes(TemplateContentTypeSelectorCM, ApplicationTypes.Excel);
            this.LoadApplicationTemplateContentTypes(TemplateContentTypeSelectorCM, ApplicationTypes.Outlook);
        }

        private void LoadApplicationTemplateContentTypes(ContextMenu cm, ApplicationTypes applicationType)
        {
            bool containsItems = false;
            MenuItem mi = new MenuItem() { Header = applicationType.ToString() };
            List<DocumentTemplate> documentTemplates = this.DocumentTemplates.GetDocumentTemplates(applicationType);

            foreach (DocumentTemplate documentTemplate in documentTemplates)
            {
                MenuItem miDocumentTemplate = new MenuItem() { Header = documentTemplate.Title };
                List<DocumentTemplateMapping> mappings = ConfigurationManager.GetInstance().GetDocumentTemplateMappings(documentTemplate.ID);

                foreach (DocumentTemplateMapping mapping in mappings)
                {
                    containsItems = true;
                    MenuItem miMapping = new MenuItem() { Header = mapping.ContentTypeName, Tag = new object[] { applicationType, documentTemplate, mapping } };
                    miMapping.Click += new RoutedEventHandler(miMapping_Click);
                    miDocumentTemplate.Items.Add(miMapping);

                    Dictionary<string, SearchFilters> searchFilters = new Dictionary<string, SearchFilters>();
                    SearchFiltersCollection.Add(mapping.ID, searchFilters);
                }

                mi.Items.Add(miDocumentTemplate);
            }

            if(containsItems == true)
                cm.Items.Add(mi);
        }

        void miMapping_Click(object sender, RoutedEventArgs e)
        {
            object[] args = (object[])((MenuItem)e.Source).Tag;
            this.SelectedApplicationType = (ApplicationTypes)args[0];
            this.SelectedDocumentTemplate = (DocumentTemplate)args[1];
            this.SelectedDocumentTemplateMapping = (DocumentTemplateMapping)args[2];

            this.CurrentSearchFilters = SearchFiltersCollection[this.SelectedDocumentTemplateMapping.ID];
            SelectedContentTypeLabel.Content = this.SelectedApplicationType.ToString() + "-" + this.SelectedDocumentTemplate.Title + "-" + this.SelectedDocumentTemplateMapping.ContentTypeName;
            SearchTextBox.Focus();
            FiltersButton.IsEnabled = true;
            SearchButton.IsEnabled = false;
            UpdateFilterButtonText();
        }

        public void Initialize(SiteSettings siteSettings, DocumentTemplates documentTemplates)
        {
            this.IsDataLoaded = false;
            this.SiteSettings = siteSettings;
            this.DocumentTemplates = documentTemplates;
        }

        public SearchExplorer()
        {
            InitializeComponent();
            SearchResultDataGridView.ContextMenu = new SearchViewItemMenu();
        }

        public bool HasAnythingToDisplay
        {
            get
            {
                return ConfigurationManager.GetInstance().GetDocumentTemplateMappings().Count > 0 ? true : false;
            }
        }


        private void FiltersButton_Click(object sender, RoutedEventArgs e)
        {
            SiteSetting siteSetting = this.SiteSettings[SelectedDocumentTemplateMapping.Folder.SiteSettingID];
            //IServiceManager serviceManager = ServiceManagerFactory.GetServiceManager(siteSetting.SiteSettingType);
            //Folder targetFolder = serviceManager.GetFolder(siteSetting, SelectedDocumentTemplateMapping.Folder);
            //ContentType contentType = serviceManager.GetContentType(siteSetting, targetFolder, SelectedDocumentTemplateMapping.ContentTypeID, false);
            SearchFiltersPanelControl searchFiltersPanelControl = new SearchFiltersPanelControl();
            searchFiltersPanelControl.Initialize(siteSetting, SelectedDocumentTemplateMapping.Folder, SelectedDocumentTemplateMapping.ContentTypeID);

            searchFiltersPanelControl.SearchFilters = this.CurrentSearchFilters;

            if (searchFiltersPanelControl.ShowDialog(null, Languages.Translate("Search Filters"), 450, 755) == true)
            {
                SearchFiltersCollection[this.SelectedDocumentTemplateMapping.ID] = searchFiltersPanelControl.SearchFilters;
                this.CurrentSearchFilters = searchFiltersPanelControl.SearchFilters;
                UpdateFilterButtonText();
            }

            CheckSearchButtonEnability();
        }

        private void UpdateFilterButtonText()
        {
            FiltersButton.Content = string.Format(Languages.Translate("Filters ({0})"), (this.CurrentSearchFilters == null ? "0" : this.CurrentSearchFilters.Count.ToString()));
        }

        private void CheckSearchButtonEnability()
        {
            if (this.SelectedDocumentTemplate != null
                && (string.IsNullOrEmpty(SearchTextBox.Text) == false || this.CurrentSearchFilters.Count > 0))
            {
                SearchButton.IsEnabled = true;
            }
            else
            {
                SearchButton.IsEnabled = false;
            }
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            SiteSetting siteSetting = this.SiteSettings[SelectedDocumentTemplateMapping.Folder.SiteSettingID];
            IServiceManager serviceManager = ServiceManagerFactory.GetServiceManager(siteSetting.SiteSettingType);
            Folder targetFolder = serviceManager.GetFolder(siteSetting, SelectedDocumentTemplateMapping.Folder);

            int itemCount;
            string listItemCollectionPositionNext = String.Empty;
            Folder selectedFolder = targetFolder;
            IView selectedView = null;
            string sortedFieldName = string.Empty;
            bool isAsc = true;
            int currentPageIndex = 0;
            string currentListItemCollectionPositionNext = "0";

            CamlFilters customFilters = new CamlFilters();
            customFilters.IsOr = false;

            foreach (string key in this.CurrentSearchFilters.Keys)
            {
                CamlFilter customFilter = new CamlFilter(this.CurrentSearchFilters[key][0]);
                customFilters.Add(customFilter);
            }

            List<IItem> items = ApplicationContext.Current.GetListItems(siteSetting, selectedFolder, selectedView, sortedFieldName, isAsc, currentPageIndex, currentListItemCollectionPositionNext, customFilters, true,false, out listItemCollectionPositionNext, out itemCount);
            //ApplicationContext.Current.BindSearchResultsToListViewControl(siteSetting, items, SearchResultDataGridView);
        }


        private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckSearchButtonEnability();
        }

        private void SelectedContentTypeLabel_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Label label = sender as Label;
            ContextMenu contextMenu = label.ContextMenu;

            if (e.ChangedButton == MouseButton.Left)
            {
                isLeftClick = true;
                contextMenu.PlacementTarget = label;
                contextMenu.IsOpen = true;
            }
            else if (e.ChangedButton == MouseButton.Right)
            {
                isLeftClick = false;
            }
        }

        private void TemplateContentTypeSelectorCM_Opened(object sender, RoutedEventArgs e)
        {
            if(isLeftClick == false)
                TemplateContentTypeSelectorCM.IsOpen = false;
        }
    }
}
